<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/11/2 10:37
 */

namespace App\Project\Auth\Token;

use App\User;
use Illuminate\Support\Str;

/**
 * Class TokenRepository
 * @package App\Project\Auth\Token
 */
class TokenRepository
{
    /**
     * @var User | \App\Models\Patient
     */
    protected $user;

    /**
     * @var string
     */
    protected $token;

    /**
     * @return string
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * @return $this
     */
    public function refresh()
    {
        $this->token = $this->generateNewToken();

        return $this;
    }

    /**
     * @param $user
     * @return $this
     */
    public function forUser($user)
    {
        $this->user = $user;
        return $this;
    }

    /**
     * @return string
     */
    public function generateNewToken()
    {
        $string = $this->user->toJson(JSON_UNESCAPED_UNICODE) . Str::random(32);

        return app('hash')->make($string);
    }

    public function then(callable $then)
    {
        $then($this->token, $this->user);

        return $this;
    }
}